#!/usr/bin/python
#-*- coding: utf-8 -*-

# subversion info:
# $HeadURL: $
# $Author: $
# $Id: $
# $Revision: $

"""
  RSS: Create rss output of events.
  Authors = Rafael Treviño <skasi.7@gmail.es>
  Date = 24/10/09
"""

# Imports externals
import os
import sys
import time
import PyRSS2Gen

# Imports internals
from Model import Event


class RSS(object):

  def __init__(self, config):
    super(RSS, self).__init__(self)
    self.__rssOutputPath = config.get('rssoutputpath')

  def syncDB(self):
    print 'Syncing RSS %s...' % self.__rssOutputPath
    rss = PyRSS2Gen.RSS2(
        title='Feedtorrent log',
        link='http://aerelon.homeunix.org/feedtorrent',
        description='Feedtorrent automated series download events',
        lastBuildDate=time.strftime('%a, %d %b %Y %H:%M:%S +0100'),
        items=[]
      )
    for event in Event.select()[-30:]:
      rss.items.append(PyRSS2Gen.RSSItem(
        guid=PyRSS2Gen.Guid(event.episode.torrentUri),
        pubDate=event.date,
        title=event.title,
        description=event.description,
      ))
    rss.items.reverse()
    rss.write_xml(open(self.__rssOutputPath, 'w'))

# Main entry point
if __name__ == '__main__':
  # TODO: Better logging and options
  try:
    rssOutputPath = os.path.abspath(sys.argv[1])
  except IndexError:
    print >> sys.stderr, 'Usage: %s <rss output path>' % sys.argv[0]
    sys.exit(1)
  if rssOutputPath:
    print >> sys.stderr, 'Using rss output path "%s"' % rssOutputPath
  else:
    print >> sys.stderr, 'Unable to determine the rss output path'
    sys.exit(1)

  rss = RSS(dict(rssoutputpath=rssOutputPath))
  rss.syncDB()

